home
diamond Go Premium
Data Engineering Path  ·  PySpark

Streaming Sources & Sinks

Structured Streaming treats real-time data streams as an unbounded table that is being continuously appended. The core API uses spark.readStream to ingest data from continuous Sources and df.writeStream to write output to streaming Sinks.

graph LR
    subgraph Ingestion["1. Streaming Sources"]
        direction TB
        S1["Kafka Topic Events"]
        S2["File Watcher Folder"]
    end
    subgraph Engine["2. Incremental Processing Engine"]
        E1["Continuous Query DSL"]
        E2["Trigger Interval (Trigger)"]
    end
    subgraph Output["3. Streaming Sinks"]
        direction TB
        O1["Storage Sink (Parquet / Delta)"]
        O2["Console Sink (Debugging)"]
    end
    Ingestion --> Engine --> Output
    style Ingestion fill:#eff6ff,stroke:#2563eb,stroke-width:2px;
    style Engine fill:#fff7ed,stroke:#ea580c,stroke-width:2px;
    style Output fill:#f0fdf4,stroke:#16a34a,stroke-width:2px;

Streaming Sources (Ingestion)

A Source represents the system feeding data into Spark:

Source Configuration Format Description
File Source spark.readStream.format("parquet\ csv\
Kafka spark.readStream.format("kafka") Connects directly to Apache Kafka topics to ingest event streams in real-time.
Rate spark.readStream.format("rate") Generates dummy rows at a specified rate per second (excellent for testing and performance benchmarks).
Socket spark.readStream.format("socket") Reads text lines from a raw TCP socket connection (primarily used for local testing).

Streaming Sinks (Storage)

A Sink represents the target storage where computed streams are written:

Sink Configuration Format Description
File Sink df.writeStream.format("parquet\ csv\
Kafka df.writeStream.format("kafka") Publishes the streaming results back as events to a Kafka topic.
Console df.writeStream.format("console") Prints the streaming rows directly to stdout/stderr on the driver terminal. Used strictly for debugging.
ForeachBatch df.writeStream.foreachBatch(user_func) A custom handler that lets you execute standard batch DataFrame writes (like inserting into PostgreSQL/Cassandra) once per stream micro-batch.

PySpark Code Example: File-Watcher Stream to Console

Here is a complete script demonstrating how to monitor a directory for new JSON file dumps and stream the results directly to the console:

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, DoubleType

# 1. Setup Spark
spark = SparkSession.builder \
    .appName("Streaming Sources and Sinks") \
    .master("local[*]") \
    .getOrCreate()

# 2. Define schema explicitly for the incoming file stream
# Streaming file sources require an explicit schema declaration!
file_schema = StructType([
    StructField("device_id", StringType(), False),
    StructField("temperature", DoubleType(), True),
    StructField("status", StringType(), True)
])

# 3. Initialize File-Watcher Read Stream
# Spark will watch the 'input stream directory' folder continuously
streaming_df = spark.readStream \
    .format("json") \
    .schema(file_schema) \
    .option("maxFilesPerTrigger", 1) \
    .load("input_stream_directory")

# 4. Filter incoming records
alert_df = streaming_df.filter(F.col("temperature") > 80.0)

# 5. Write Stream to Console Sink (for testing)
# We specify 'checkpointLocation' to track micro-batch offsets for recovery
query = alert_df.writeStream \
    .format("console") \
    .outputMode("append") \
    .option("checkpointLocation", "temp_checkpoints") \
    .start()

# 6. Keep the stream active until terminated
query.awaitTermination()
Find this content helpful? ☕ Buy me a coffee

Entity Details

Create New Item

celebration
Enjoying the free content?

Create a free account to track your progress and save your place.

Create Free Account
help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.